package com.KMGSoftworks.ShoppingList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Lists extends ListActivity {

	private static final String TAG = "ShoppingList";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        
        ListView lv = getListView();
        lv.setOnCreateContextMenuListener(this);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        		showItems(position, id);
        	}   	
		});
         
       getData();
     }
     
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        	case R.id.mnuNewList:
        		createList();
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
    	if(v.getId() == android.R.id.list){
    		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    		CharSequence title = ((TextView) info.targetView.findViewById(R.id.txtListName)).getText();
    		menu.setHeaderTitle(title);
    		MenuInflater mi = getMenuInflater();
    		mi.inflate(R.menu.menu_listcontext, menu);
    	}
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item){
    	final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	switch(item.getItemId()) {
    		case R.id.deleteList:
    			AlertDialog alert = new AlertDialog.Builder(this).create();
    			alert.setTitle("Delete");
    			alert.setMessage("Are you sure?");
    			alert.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						Cursor c = (Cursor)getListView().getAdapter().getItem(info.position);
						deleteData(c.getInt(0));
					}
				});
    			alert.setButton2("Cancel", new DialogInterface.OnClickListener() {
    			      public void onClick(DialogInterface dialog, int which) {
    			        return;
    			    }}); 

    			alert.show();
		  		break;
		  	case R.id.renameList:
		  		Toast r = Toast.makeText(getApplicationContext(), "Rename", Toast.LENGTH_SHORT);
		  		r.setGravity(Gravity.TOP, 0,0);
    			r.show();
		  		break;
		  	default:
		  		return super.onContextItemSelected(item);
	  }
   	  return true;
   	}
    
    private void createList(){
    	Intent intent = new Intent(Constants.CREATE_LIST_ACTIVITY);
    	startActivityForResult(intent, Constants.CREATE_LIST_CODE);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	if(requestCode == Constants.CREATE_LIST_CODE && resultCode == RESULT_OK){
    		String listName = data.getStringExtra("ListName");
    		if(listName.length() != 0){
    			Log.d(TAG, listName);
				if(CheckIfListExists(listName) == false){
					ContentValues values = new ContentValues(); 
					values.put(ShoppingList.List.COLUMN_NAME_NAME, listName);
					Uri uri = getContentResolver().insert(ShoppingList.List.CONTENT_URI, values);
					Log.i(TAG, "insert - " + uri.toString());
				}
				else{
		  			AlertDialog alert = new AlertDialog.Builder(this).create();
	    			alert.setTitle("Add New List");
	    			alert.setMessage(listName + " already exists! Add canceled.");
	       			alert.setButton("Ok", new DialogInterface.OnClickListener() {
	    			      public void onClick(DialogInterface dialog, int which) {
	    			        return;
	    			    }}); 

	    			alert.show();
				}
    		}
    	}
    }
    
    private boolean CheckIfListExists(String listName) {

    	String[] args = new String[] {listName};
    	Cursor c = getContentResolver().query(
    			ShoppingList.List.CONTENT_URI, 
    			null, 
    			ShoppingList.List.SELECTION, 
    			args, 
    			null);
    	
    	return c != null && c.getCount() > 0;
    	
	}

  	private void showItems(int position, long id){
    	ListView lv = getListView();
    	Cursor c = (Cursor)lv.getItemAtPosition(position);
    	Intent intent = new Intent(Constants.VIEW_LIST_ITEMS_ACTIVITY); 
    	intent.putExtra(Constants.ListID, c.getInt(0));
    	intent.putExtra(Constants.ListName, c.getString(1));
    	intent.putExtra(Constants.ListCount, c.getInt(2));
    	
    	startActivity(intent);
    }
    
    private void deleteData(int row_id){
    	Uri listUri = ContentUris.withAppendedId(ShoppingList.List.CONTENT_ID_URI_PATTERN, row_id);
    	Log.i(TAG, "delete - " + listUri.toString());
    	getContentResolver().delete(listUri, null, null);
    }
    
    private void getData() {
       
    	Cursor c = getContentResolver().query(
    			ShoppingList.List.CONTENT_URI, 
    			null, 
    			null, 
    			null, 
    			ShoppingList.List.DEFAULT_SORT_ORDER);
    	
    	startManagingCursor(c);

   	
    	int[] viewIDs = new int[] { R.id.txtListID,  R.id.txtListName, R.id.txtListCount };
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
        		this,
        		R.layout.list_row,
        		c,
        		ShoppingList.List.LIST_PROJECTION,
        		viewIDs);
        
        setListAdapter(adapter);
	

	}

}